﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;

namespace mbine.msgc.model
{
    /// <summary>
    /// 인증 서버
    /// </summary>
    public class CAuthenServer : CWebServer
    {
        public CAuthenServer(string _servername, string _path)
        {
            this.ServerName = _servername;
            this.Path = _path;
        }

        public void Request(string _email, string _password, string _pkey)
        {
            Dictionary<string, string> param = new Dictionary<string, string>{
                {"authkey", ""}, 
                {"mode", "login"}, 
                {"data", "{\"id\" : \"" + _email + "\", \"pwd\" : \"" + _password + "\", pkey : \"" + _pkey + "\"}"}
            };

            Send(param);
        }
    }

    /// <summary>
    /// Roster 서버
    /// </summary>
    public class CRosterServer : CWebServer
    {
        public CRosterServer()
        {
            this.ServerName = "ma165.mailplug.co.kr";
            this.Path = "/_roster.php";
        }

        public void Request(string _domain)
        {
            Dictionary<string, string> param = new Dictionary<string, string>{
                {"domain", _domain}
            };

            this.Send(param);
        }
    }

    /// <summary>
    /// 웹 서버(추상)
    /// </summary>
    public abstract class CWebServer : CServer
    {
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        public string Path { get; set; }
        public string Method { get; set; }
        public string GetData { get; set; }
        public event EventHandler DataReceived;
        public event EventHandler EventError;

        Dictionary<string, string> parameter;

        public CWebServer()
        {
            this.Method = "POST";
            this.ServerPort = 80;
        }

        public virtual void Send(Dictionary<string, string> _parameter)
        {
            this.Send(this.Path, _parameter);
        }

        public virtual void Send(string _path, Dictionary<string, string> _parameter)
        {
            string data = "";

            parameter = _parameter;
            if (_path != "")
            {
                WebRequest myWebRequest = WebRequest.Create("http://" + this.ServerName + _path);
                RequestState myRequestState = new RequestState();
                myRequestState.request = myWebRequest;
                myWebRequest.ContentType = "application/x-www-form-urlencoded";
                myRequestState.request.Method = "POST";

                IAsyncResult r = (IAsyncResult)myWebRequest.BeginGetRequestStream(
                    new AsyncCallback(ReadCallback), myRequestState);

                allDone.WaitOne();
                try
                {
                    WebResponse myWebResponse = myWebRequest.GetResponse();

                    Stream streamResponse = myWebResponse.GetResponseStream();
                    StreamReader streamRead = new StreamReader(streamResponse);
                    Char[] readBuff = new Char[256];
                    int count = streamRead.Read(readBuff, 0, 256);

                    while (count > 0)
                    {
                        data += new String(readBuff, 0, count);
                        count = streamRead.Read(readBuff, 0, 256);
                    }
                    GetData = data;

                    CLog.Instance.WLog(data);

                    streamResponse.Close();
                    streamRead.Close();
                    myWebResponse.Close();

                    if (DataReceived != null)
                        DataReceived(this, null);
                }catch(WebException e){
                    GetData = "{\"result\":\"1\",\"msg\":\"로그인 성공\",\"authkey\":\"C9AE7238AAB08598B4166DC9771DE7D5\",\"roster\":{\"part\":[{\"Code\":\"1\",\"Name\":\"기획\",\"PartCode\":\"2\"},{\"Code\":\"2\",\"Name\":\"개발\",\"PartCode\":\"1\"},{\"Code\":\"3\",\"Name\":\"영업\",\"PartCode\":\"2\"},{\"Code\":\"4\",\"Name\":\"회계\",\"PartCode\":\"3\"}],\"user\":[{\"Code\":\"1\",\"Email\":\"hitapia@gmail.com\",\"Name\":\"방성원\",\"PartCode\":\"2\"},{\"Code\":\"2\",\"Email\":\"hitapia1@gmail.com\",\"Name\":\"방성원1\",\"PartCode\":\"1\"},{\"Code\":\"3\",\"Email\":\"hitapia2@gmail.com\",\"Name\":\"방성원2\",\"PartCode\":\"3\"},{\"Code\":\"4\",\"Email\":\"hitapia3@gmail.com\",\"Name\":\"방성원3\",\"PartCode\":\"3\"},{\"Code\":\"5\",\"Email\":\"hitapia4@gmail.com\",\"Name\":\"방성원4\",\"PartCode\":\"4\"},{\"Code\":\"6\",\"Email\":\"hitapia5@gmail.com\",\"Name\":\"방성원5\",\"PartCode\":\"4\"},{\"Code\":\"7\",\"Email\":\"hitapia6@gmail.com\",\"Name\":\"방성원6\",\"PartCode\":\"4\"},{\"Code\":\"8\",\"Email\":\"hitapia7@gmail.com\",\"Name\":\"방성원7\",\"PartCode\":\"1\"},{\"Code\":\"9\",\"Email\":\"hitapia8@gmail.com\",\"Name\":\"방성원8\",\"PartCode\":\"2\"}]}}";
                    if (DataReceived != null)
                        DataReceived(this, null);
                }
            }
        }

        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            string param = "0=0";
            RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
            WebRequest myWebRequest = myRequestState.request;

            Stream streamResponse = myWebRequest.EndGetRequestStream(asynchronousResult);
            string postData = Console.ReadLine();

            if (parameter.Count > 0)
            {
                foreach (KeyValuePair<string, string> p in parameter)
                    param = param + "&" + p.Key + "=" + p.Value;
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(param);
            streamResponse.Write(byteArray, 0, param.Length);
            streamResponse.Close();
            allDone.Set();
        }
    }

    public class RequestState
    {
        public WebRequest request;
        public RequestState()
        {
            request = null;
        }
    }
}
